// 路由拦截

// 导入路由
import { Message } from 'element-ui'
import router from './router'
// Store
import store from './store'
// 导入读取Token方法
import { getToken } from './utils/auth'

// 定义路由白名单
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  console.log('Roles  ----->  ', store.getters.roles)
  if (getToken()) {
    // 判断用户既有Token去的也是登录页面
    if (to.path === '/login') {
      next({ path: '/' })
    } else if (store.getters.roles.length === 0) {
      store.dispatch('getUserInfo').then(res => {
        store.dispatch('generateRoutes').then(accessRoutes => {
          console.log(' accessRoutes ----->  ', accessRoutes)
        })
      })
        .then(res => {
          console.log('用户信息  ----->  ', res)
          next()
        }).catch(error => {
          Message.error(error)
        })
    } else {
      next()
    }
  } else if (whiteList.indexOf(to.path) !== -1) {
    next()
  } else {
    next(`/login?redirect=${to.fullPath}`)
  }
})
